package cn.com.utt.common.http;

import java.util.Base64;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

public class Client {

	public String doPostWithJson(String url, String params) {
		try {
			System.out.println("doPost:" + params);
			CloseableHttpClient httpclient = HttpClients.createDefault();
			HttpPost post = new HttpPost(url);
			post.setHeader("Content-type", "application/json");
			post.setEntity(new StringEntity(params, "utf-8"));
			HttpResponse response = httpclient.execute(post);
			return EntityUtils.toString(response.getEntity(), "utf-8");
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}

	public String doGetWithJson(String url) {
		try {
			CloseableHttpClient httpClient = HttpClients.createDefault();
			HttpGet get = new HttpGet(url);
			get.setHeader("Content-type", "application/json");
			HttpResponse response = httpClient.execute(get);
			return EntityUtils.toString(response.getEntity(), "utf-8");

		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}

	public String doGetNoJson(String url) {
		try {
			CloseableHttpClient httpClient = HttpClients.createDefault();
			HttpGet get = new HttpGet(url);
			HttpResponse response = httpClient.execute(get);
			return EntityUtils.toString(response.getEntity(), "utf-8");

		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}

	public String doGetWithJsonAndBasic(String url) {
		try {
			String auth = "admin" + ":" + "public";
			String encode = Base64.getEncoder().encodeToString(auth.getBytes());
			CloseableHttpClient httpClient = HttpClients.createDefault();

			HttpGet get = new HttpGet(url);
			get.setHeader("Content-type", "application/json");
			get.addHeader("Authorization", "Basic " + encode);
			HttpResponse response = httpClient.execute(get);
			return EntityUtils.toString(response.getEntity(), "utf-8");

		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}
}
